package com.sharer.last.base.support;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.sharer.last.base.model.PageQueryDTO;

import com.sharer.last.base.utils.BaseUtil;
import com.sharer.last.base.utils.StringUtil;


import java.util.Map;
import java.util.Optional;

public class QueryCondition {

    /**
     * 转化成mybatis plus中的Page
     *
     * @param query
     * @return
     */
    public static <T> IPage<T> getPage(PageQueryDTO query) {
        Page<T> page        = new Page<>(BaseUtil.toInt(query.getPage(), 1), BaseUtil.toInt(query.getLimit(), 10));
        String  orderColumn = query.getOrderColumn();
        if (StringUtil.isNotBlank(orderColumn)) {
            OrderItem orderItem = new OrderItem();
            orderItem.setColumn(query.getOrderColumn());
            Boolean asc = Optional.ofNullable(query.getAsc()).orElse(true);
            orderItem.setAsc(asc);
        }
        return page;
    }

    /**
     * 转化成mybatis plus中的Page
     *
     * @param query
     * @return
     */
    public static Page getPageQuery(PageQueryDTO query) {
        Page   page        = new Page<>(BaseUtil.toInt(query.getPage(), 1), BaseUtil.toInt(query.getLimit(), 10));
        String orderColumn = query.getOrderColumn();
        if (StringUtil.isNotBlank(orderColumn)) {
            OrderItem orderItem = new OrderItem();
            orderItem.setColumn(query.getOrderColumn());
            Boolean asc = Optional.ofNullable(query.getAsc()).orElse(true);
            orderItem.setAsc(asc);
        }
        return page;
    }

    /**
     * 获取mybatis plus中的QueryWrapper
     *
     * @param entity
     * @param <T>
     * @return
     */
    public static <T> QueryWrapper<T> getQueryWrapper(T entity) {
        return new QueryWrapper<>(entity);
    }

    /**
     * 获取mybatis plus中的QueryWrapper
     *
     * @param query
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> QueryWrapper<T> getQueryWrapper(Map<String, Object> query, Class<T> clazz) {
        query.remove("page");
        query.remove("limit");
        QueryWrapper<T> qw = new QueryWrapper<>();
        qw.setEntity(BaseUtil.newInstance(clazz));
        if (BaseUtil.isNotEmpty(query)) {
            query.forEach((k, v) -> {
                if (BaseUtil.isNotEmpty(v)) {
                    qw.like(BaseUtil.humpToUnderline(k), v);
                }
            });
        }
        return qw;
    }


}
